import {createMemoryHistory, createRouter, createWebHistory} from 'vue-router'
import layout from '@/views/layout/index.vue'
const constantRoute  = [
    {
      path: '/login',
      component: () => import('@/views/login/index.vue'),
      meta: { title: '登录',name: '登录', hidden: true }
    },
    //laytou
    {
        path: '/',
        component: layout,
        name: 'layout',
        redirect: '/index',
        meta: { title: 'layout',name: 'layout', icon: 'Layout', hidden: true},
        children: [
            {
                path: '/index',
                component: ()=> import('@/views/index/index.vue'),
                name: 'index',
                meta: { title: '首页',name: '首页', icon: 'House', hidden: false}
            },
            //动态路由添加到这里
        ]
    }
]
//动态路由
const daynRoute = [
    {
        path: '/pos',
        hidden: false,
        name: '店铺管理',
        meta: {icon: 'TakeawayBox',title: '店铺管理', hidden: false},
        component: layout,
        children : [
            {path: '/setting', name: 'posStting', component: '/pos/setting/index.vue', meta: {title: '店铺设置', icon: 'Setting', hidden: false}},
            {path: '/edid', name: 'posEdit', component: '/pos/edid/index.vue', meta: {title: '店铺编辑', icon: 'Edit', hidden: false}},
            {path: '/address', name: 'posAddress', component: '/pos/address/index.vue', meta: {title: '店铺地址', icon: 'Location', hidden: false}},
            {path: '/authentication', name: 'posAuthentication', component: '/pos/authentication/index.vue', meta: {title: '店铺认证', icon: 'Verification', hidden: false}},
            {path: '/recommend', name: 'posRecommend', component: '/pos/recommend/index.vue', meta: {title: '商品推荐', icon: 'Recommend', hidden: false}},
        ]
    }
]

function addRouter(r, routes, layoutName){
    const layoutRoute = router.getRoutes().find(item => item.name === layoutName);
    if (layoutRoute && layoutRoute.children){
        routes.forEach((route) => {
            // 处理组件字符串，动态导入组件
            if (typeof route.component === 'string') {
                route.component = () => import(`@/views/${route.component}.vue`);
            }
            // 添加当前路由到 layout 的 children
            layoutRoute.children.push(route);
            // 如果存在子路由，递归调用（但通常后端返回的路由已经是扁平化的）
            if (route.children && route.children.length > 0) {
                // 这里你可能需要递归处理，但通常后端返回的路由已经是扁平化的
                addRouter(router, route.children, layoutName); // 如果需要的话
            }
            router.addRoute(route);
        });
    }
}

const router = createRouter({
    history: createWebHistory(),
    routes: constantRoute,
})



router.beforeEach((to, from, next)=> {
    addRouter(router, daynRoute, 'layout')
    next()
})
export default router
